﻿using System;
using System.IO;
using System.Reflection;
using System.Text;

namespace NUnit4PowerShell
{
    public class Logger
    {
        public const string LogFileName = "NUnit4PowerShell.log";
        private const string DatePattern = "yyyy-MM-dd HH:mm:ss,ms";
        private readonly string _logPath;
        private readonly bool _isLoggerActivated;

        private Logger()
        {
            _isLoggerActivated = Utils.IsLoggerActivated();
            if (!_isLoggerActivated)
            {
                return;
            }
            Uri u = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            string dir = System.IO.Path.GetDirectoryName(u.LocalPath);

            _logPath = System.IO.Path.Combine(dir, LogFileName);
            if (File.Exists(_logPath))
            {
                File.Delete(_logPath);
            }
            WriteLog("Logger initialization");
        }

        public void Info(string msg)
        {
            msg = DateTime.Now.ToString(DatePattern) + " [INFO]  " + msg;
            WriteLog(msg);
        }

        public void AddEmptyLine()
        {
            WriteLog("");
        }

        public void Info(string msg, string source)
        {
            msg = DateTime.Now.ToString(DatePattern) + " [" + source + "]" + " [INFO]  " + msg;
            WriteLog(msg);
        }

        public void Error(string msg)
        {
            msg = DateTime.Now.ToString(DatePattern) + " [ERROR] " + msg;
            WriteLog(msg);
        }

        public void Error(string msg, string source)
        {
            msg = DateTime.Now.ToString(DatePattern) + " [" + source + "]" + " [ERROR] " + msg;
            WriteLog(msg);
        }

        private void WriteLog(string msg)
        {
            if (_isLoggerActivated)
            {
                File.AppendAllText(_logPath, msg + Environment.NewLine, Encoding.UTF8); ;
            }
        }

        private static Logger instance;

        public static Logger Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new Logger();
                }
                return instance;
            }
        }
    }
}
